/**
* @Author: Zhengfeng.Yao
* @Date:   2017-01-23 14:12:23
* @Last modified by:   Zhengfeng.Yao
* @Last modified time: 2017-02-09 14:49:27
*/

import React, { Component } from 'react';
import cn from 'classnames';
import './fileUpload.less';

function FileItem({file, onRemove}) {
  return (
    <div key={file.path} className="aegis-fileUpload-list-item">
      <div className="aegis-fileUpload-list-item-info">
        <i className="anticon"/>
        {file.path}
        <i className="anticon aegis-fileUpload-list-item-info-remove" onClick={onRemove || (() => {})}/>
      </div>
    </div>
  );
}

export default class FileUpload extends Component {
  static FileItem = FileItem;

  constructor(props) {
    super(props);
    this.state = {
      isUploading: false
    };
  }

  onClick = e => {
    const el = this.refs.file;
    if (!el) {
      return;
    }
    this.props.onUploadClick();
    if (this._timer) {
      return;
    }
    this.setState({isUploading: true});
    const _this = this;
    this._timer = setTimeout(() => {
      el.click();
      setTimeout(() => {
        this._timer = null;
        this.props.onUploadChange();
        this.setState({isUploading: false});
      }, 2000)
    }, 0);
  };

  onChange = e => {
    if (e.target.value) {
      const filePath = e.target.value.slice(0, e.target.value.lastIndexOf('\\'));
      const files = Array.prototype.slice.call(e.target.files);
      files.forEach(file => {
        file.path = `${filePath}${'\\'}${file.name}`;
      })
      this.props.onUploadChange(files);
      this.setState({isUploading: false});
      e.target.value = "";
    }
  };

  render() {
    const { accept, tip, children } = this.props;
    return (
      <div className="aegis-fileUpload">
        <div className="aegis-fileUpload-select">
          <span onClick={this.onClick}>
            <input
              type="file"
              ref="file"
              multiple
              onChange={this.onChange}
              style={{display: 'none'}}/>
            <button style={{cursor: this.state.isUploading ? 'wait' : 'pointer'}}>
              <i className="anticon"/>
              添加文件
            </button>
          </span>
          {
            tip
          }
        </div>
        <div className="aegis-fileUpload-list">
          {children}
        </div>
      </div>
    );
  }
}
